<template>
  <div class="treeBox">
    <el-input v-model="filterText" style="width: 240px" placeholder="请输入节点名称" />
    <el-tree @check-change="handleCheckChange" show-checkbox ref="treeRef" style="max-width: 800px" class="filter-tree"
      :data="dataTree" :filter-node-method="filterNode"
     default-expand-all node-key="id" />
  </div>
</template>

<script>
import { ref, onMounted, watch, nextTick, watchEffect,defineProps } from 'vue'
import { DyCpAllManageTree, postthreesiteName } from '../../src/http/http'
import bus from '../tools/eventBus/'

export default {
  setup() {
    const dataTree = ref([]); // 树的一级节点
    const filterText = ref(''); // 搜索过滤文本
    const treeRef = ref(null); // 树的引用
    const checkBox2true = ref([]); // 存储选中的复选框数据
    const checkBoxtrue = ref([]); // 存储选中的复选框数据
    const treeLable = ref([]); // 存储选中的复选框lable
    const treeDataType = ref('')
    const firstInitSites = ref([]);
    const isFirstTime = ref(true)


//  isFirstTime.value = localStorage.getItem('threeType')

    // console.log(isFirstTime.value);
    
    // 监听来自父组件的复选框状态更新
bus.on('checkBox', async (data) => {
  // 更新选中复选框的数据
  if (isFirstTime.value) {
    // 更新选中复选框的数据
  // console.log(data.revriced,'99999999999999999999999999');

  checkBox2true.value = [...data.revriced];

  
    isFirstTime.value = false; // 将标志变量设为 false，表示已经赋值过一次
  }
  nextTick(() => {
        if (treeRef.value) {
          // 动态勾选节点
          treeRef.value.setCheckedKeys(checkBox2true.value);
        }
      }); 
  checkBoxtrue.value =  [...data.revriced];
  isFirstTime.value = data.three
  console.log('接收到的复选框数据:', checkBox2true.value);

});

    // 请求数据并构建树形结构
    onMounted(async () => {
      try {
        // 获取站点类型
        const treeRes = await DyCpAllManageTree({
          dataChange: [],
          variableChange: null,
        });

        // 获取站点名称
        const siteRes = await postthreesiteName({
          entityFilter: {
            FilterConditions: [],
            SortConditions: [],
            IsUsePagination: true,
            Pagination: {
              PageIndex: 1,
              PageSize: 20,
              PageCount: 0,
              TotalCount: 0,
            },
          },
          requestInfo: {
            dataChange: [],
            variableChange: null,
          },
        });

        // 格式化数据并更新树
        const formattedData = formatData(
          treeRes.data.returnValue.result,
          siteRes.data.returnValue.result
        );
        dataTree.value = formattedData;
        console.log(dataTree.value,'树形结构');
        
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    });
    // 格式化树形数据的函数
    const formatData = (treeData, siteData) => {
      const result = [];
      const map = new Map();

      // 初始化所有一级节点
      treeData.forEach((item) => {
        const node = { id: item.id, label: item.name, children: [] };
        map.set(item.pathInfo.path, node);
      });

      // 将站点名称数据加入到树形结构中
      siteData.forEach((item) => {
        const node = map.get(item.category.category_PathInfo.path);
        if (node) {
          node.children.push({
            id: item.id, // 确保这个 id 唯一
            label: item.name,
          });
        }
      });

      // 将没有父节点的元素作为根节点
      map.forEach((value, key) => {
        const parts = key.match(/.{1,4}/g) || [];
        if (parts.length === 1) {
          result.push(value); // 根节点
        } else {
          const parentPath = parts.slice(0, -1).join(''); // 找到父节点路径
          const parentNode = map.get(parentPath);
          if (parentNode) {
            parentNode.children.push(value); // 添加到父节点的 children 中
          }
        }
      });
      
      return result;
    };

    
    
    // 过滤节点函数
    const filterNode = (value, data) => {
      if (!value) return true;
      return data.label.toLowerCase().includes(value.toLowerCase());
    };
    // 监听过滤输入的变化并更新树过滤
    watch(filterText, (val) => {
      if (treeRef.value) {
        treeRef.value.filter(val);
      }
    });
    // const localIsFirstTime = ref(props.isFirstTime);
    // 监听 props 变化，当父组件传入新的值时，更新子组件的值
// watch(() => props.isFirstTime, (newValue) => {
//   localIsFirstTime.value = newValue;
//   console.log('isFirstTime updated to:', newValue);
// });

    //处理复选框选中状态变化
    // const checkBox2 = (checkedKeys, checkedNodes) => {
    //   console.log('复选框变化:', checkedKeys);
    //   bus.emit('checkData', { checkData: checkedKeys });
    // };

    const handlesetChecked =(data, checked, deep) =>{
  // console.log(data ,checked,deep);
  
    }

    const handleCheckChange = (treeNode) => {
      console.log(treeNode)
      if(!treeNode.children || treeNode.children.length == 0) {
        if(checkBoxtrue.value.includes(treeNode.id)) {
          checkBoxtrue.value = checkBoxtrue.value.filter(id => id !== treeNode.id);
        } else {
          checkBoxtrue.value.push(treeNode.id);
        }

        if(treeLable.value.includes(treeNode.label)) {
          treeLable.value = treeLable.value.filter(label => label !== treeNode.label);
        } else {
          treeLable.value.push(treeNode.label);
        }

console.log( checkBoxtrue.value,'oooo');

        // console.log({
          // originSites : checkBox2true.value.filter(item => !checkBoxtrue.value.includes(item)),
          // checkedSites : checkBoxtrue.value.filter(item => !checkBox2true.value.includes(item))
        // }, '需要传输的数据')
        //编辑需要的参数
        bus.emit('schemEditdate', {
                            originSites:checkBox2true.value.filter(item => !checkBoxtrue.value.includes(item)),
                            checkedSites:  checkBoxtrue.value.filter(item => !checkBox2true.value.includes(item)),
                            sitename:treeLable.value
                          });
        bus.emit('checkData', { checkData: checkBoxtrue.value, checkName:treeLable.value });
      }

      // console.log(checkBox2true.value,'旧数据');
      
        
    }
    return {
      dataTree,
      filterText,
      treeRef,
      filterNode,
      checkBox2true,
      handleCheckChange,
      handlesetChecked,
    };
  },
};
</script>

<style scoped>
.treeBox {
  margin: 20px;
}
</style>
